<!DOCTYPE html>
<html>
<head>
    <title>Markdown文章新增</title>
    {% include 'system/common/header.html' %}
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/ppress/css/ppress.css') }}"/>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/layui/css/layui.css') }}"/>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/easymde/css/easymde.min.css') }}"/>
    <style>
        .markdown-editor {
            border: 1px solid #e6e6e6;
            border-radius: 2px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 14px;
            line-height: 1.6;
        }
        
        .markdown-preview {
            border: 1px solid #e6e6e6;
            border-radius: 2px;
            padding: 15px;
            background-color: #fafafa;
            min-height: 400px;
        }
        
        .editor-container {
            display: flex;
            gap: 20px;
        }
        
        .editor-panel {
            flex: 1;
        }
        
        .preview-panel {
            flex: 1;
        }
        
        .panel-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
        }
        
        /* EasyMDE编辑器样式调整 */
        .EasyMDEContainer {
            border: 1px solid #e6e6e6;
            border-radius: 2px;
        }
        
        .EasyMDEContainer .CodeMirror {
            height: 400px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 14px;
            line-height: 1.6;
        }
        
        .EasyMDEContainer .editor-toolbar {
            border-bottom: 1px solid #e6e6e6;
        }
        
        .EasyMDEContainer .editor-toolbar button {
            color: #666;
        }
        
        .EasyMDEContainer .editor-toolbar button:hover {
            background: #f5f5f5;
        }
        
        .EasyMDEContainer .editor-toolbar button.active {
            background: #1e9fff;
            color: #fff;
        }
    </style>
</head>
<body>
<form class="layui-form" action="">
    <input type="hidden" name="type" id="article-type" value="markdown">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">文章名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="文章标题"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">文章别名</label>
                    <div class="layui-input-block">
                        <input type="text" name="slug" lay-verify="required" autocomplete="off" placeholder="别名"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">分类目录</label>
                    <div class="layui-input-block">
                        <div class="layui-input-inline" style="width: 100%;">
                            <input type="text" id="category-display" placeholder="请选择分类" readonly class="layui-input" style="cursor: pointer;">
                            <input type="hidden" name="category_id" id="category-id" lay-verify="required">
                        </div>
                        <div id="category-tree" style="display: none; position: absolute; z-index: 1000; background: white; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); max-height: 300px; overflow-y: auto; width: 100%;">
                            <div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
                                <input type="text" id="category-search" placeholder="搜索分类..." class="layui-input" style="height: 32px; font-size: 12px;">
                            </div>
                            <div id="category-tree-content"></div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">标签</label>
                    <div class="layui-input-block">
                        <div id="tag-container" class="layui-form-mid">
                            <div class="layui-btn-group" id="selected-tags"></div>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="add-tag-btn">
                                <i class="layui-icon layui-icon-add-1"></i> 添加标签
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章摘要</label>
                    <div class="layui-input-block">
                        <textarea placeholder="文章摘要" name="excerpt" class="layui-textarea"></textarea>
                    </div>
                </div>
                
                <!-- 特色图像 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">特色图像</label>
                    <div class="layui-input-block">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <input type="text" name="featured_image" id="featured-image-url" placeholder="请输入图片地址或上传图片" class="layui-input">
                            </div>
                            <div class="layui-col-md6">
                                <button type="button" class="layui-btn layui-btn-primary" id="upload-featured-image">
                                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="paste-image-url">
                                    <i class="layui-icon layui-icon-link"></i> 粘贴地址
                                </button>
                            </div>
                        </div>
                        <div id="featured-image-preview" style="margin-top: 10px; display: none;">
                            <img id="preview-img" src="" alt="特色图像预览" style="max-width: 300px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 2px;">
                            <div style="margin-top: 5px;">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="remove-featured-image">
                                    <i class="layui-icon layui-icon-close"></i> 移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">文章内容</label>
                    <div class="layui-input-block">
                        <div class="editor-container">
                            <div class="editor-panel">

                                <textarea id="markdown-editor" name="content" placeholder="请输入Markdown内容..."></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- SEO信息 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_title" placeholder="SEO标题（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_keywords" placeholder="SEO关键词，多个关键词用逗号分隔（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">SEO描述</label>
                    <div class="layui-input-block">
                        <textarea name="meta_description" placeholder="SEO描述（可选）" class="layui-textarea" style="height: 80px;"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="post-save">
                <i class="layui-icon layui-icon-ok"></i>
                草稿
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="publish-btn">
                <i class="layui-icon layui-icon-release"></i>
                发布
            </button>
        </div>
    </div>
</form>

<script src="{{ url_for('admin.static', filename='system/component/layui/layui.js') }}"></script>
<script src="{{ url_for('admin.static', filename='system/component/easymde/js/easymde.min.js') }}"></script>
<script>
// 全局变量
let selectedTags = [];
let allTags = [];
let easyMDE; // EasyMDE编辑器实例

// 获取URL参数并设置文章类型
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

// 初始化函数
function initializePage() {
    layui.use(['form', 'jquery', 'layer', 'tree'], function() {
        let form = layui.form;
        let $ = layui.jquery;
        let layer = layui.layer;
        let tree = layui.tree;
        
        // 设置文章类型
        var articleType = getUrlParameter('type') || 'markdown';
        $('#article-type').val(articleType);
        console.log('文章类型:', articleType);

        // 初始化EasyMDE编辑器
        function initEasyMDE() {
            easyMDE = new EasyMDE({
                element: document.getElementById('markdown-editor'),
                spellChecker: false,
                placeholder: '请输入Markdown内容...',
                toolbar: [
                    'undo','redo','bold', 'italic','strikethrough', 'heading-1', 'heading-2','heading-3', '|',
                    'code','quote', 'unordered-list', 'ordered-list', '|',
                    'table','horizontal-rule',
                    'link', 'upload-image', '|',
                    'preview', 'side-by-side', 'fullscreen', '|',
                    'guide'
                ],
                status: ['lines', 'words', 'cursor'],
                autofocus: false,
                previewImagesInEditor: true,
                uploadImage: true,
                imageUploadFunction: function(file, onSuccess, onError) {
                    console.log('EasyMDE上传图片:', file.name, file.size);
                    
                    // 验证文件类型
                    if (!file.type.startsWith('image/')) {
                        onError('请选择图片文件');
                        return;
                    }
                    
                    // 验证文件大小（限制为10MB）
                    const maxSize = 10 * 1024 * 1024; // 10MB
                    if (file.size > maxSize) {
                        onError('图片文件大小不能超过10MB');
                        return;
                    }
                    
                    // 创建FormData对象
                    let formData = new FormData();
                    formData.append('image', file);
                    formData.append('type', 'images');
                    
                    // 上传文件
                    $.ajax({
                        url: '/admin/cms/post/upload',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.errorCode === 0) {
                                let imageUrl = result.data.src;
                                console.log('图片上传成功:', imageUrl);
                                onSuccess(imageUrl);
                            } else {
                                console.error('图片上传失败:', result.msg);
                                onError(result.msg || '图片上传失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('图片上传失败:', error);
                            onError('图片上传失败: ' + error);
                        }
                    });
                },
                renderingConfig: {
                    singleLineBreaks: false,
                    codeSyntaxHighlighting: true,
                },
                minHeight: '400px',
                maxHeight: '600px',
                theme: 'default'
            });
            
            // 添加粘贴图片功能
            addPasteImageSupport();
            
            console.log('EasyMDE编辑器初始化完成');
        }
        
        // 添加粘贴图片支持
        function addPasteImageSupport() {
            // 监听粘贴事件
            document.addEventListener('paste', function(e) {
                // 检查是否有图片数据
                const items = e.clipboardData.items;
                if (!items) return;
                
                for (let i = 0; i < items.length; i++) {
                    const item = items[i];
                    
                    // 检查是否是图片类型
                    if (item.type.indexOf('image') !== -1) {
                        e.preventDefault(); // 阻止默认粘贴行为
                        
                        const file = item.getAsFile();
                        if (file) {
                            console.log('检测到粘贴的图片:', file.name, file.size);
                            
                            // 显示上传提示
                            layer.msg('正在上传粘贴的图片...', {icon: 16, time: 0});
                            
                            // 上传图片
                            uploadPastedImage(file);
                        }
                        break;
                    }
                }
            });
        }
        
        // 上传粘贴的图片
        function uploadPastedImage(file) {
            // 创建FormData对象
            let formData = new FormData();
            formData.append('image', file);
            formData.append('type', 'images');
            
            // 上传文件
            $.ajax({
                url: '/admin/cms/post/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(result) {
                    layer.closeAll('loading'); // 关闭加载提示
                    
                    if (result.errorCode === 0) {
                        let imageUrl = result.data.src;
                        console.log('图片上传成功:', imageUrl);
                        
                        // 在编辑器中插入图片
                        insertImageToEditor(imageUrl);
                        
                        layer.msg('图片上传成功', {icon: 1});
                    } else {
                        layer.msg(result.msg || '图片上传失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    layer.closeAll('loading'); // 关闭加载提示
                    console.error('图片上传失败:', error);
                    layer.msg('图片上传失败: ' + error, {icon: 2});
                }
            });
        }
        
        // 在编辑器中插入图片
        function insertImageToEditor(imageUrl) {
            if (!easyMDE) return;
            
            // 获取当前光标位置
            const cursor = easyMDE.codemirror.getCursor();
            
            // 构建Markdown图片语法
            const imageMarkdown = `![图片](${imageUrl})`;
            
            // 在光标位置插入图片
            easyMDE.codemirror.replaceRange(imageMarkdown, cursor);
            
            // 将光标移动到图片后面
            easyMDE.codemirror.setCursor({
                line: cursor.line,
                ch: cursor.ch + imageMarkdown.length
            });
            
            // 聚焦编辑器
            easyMDE.codemirror.focus();
        }
        
        // 初始化EasyMDE
        initEasyMDE();

        // 加载分类数据
        function loadCategories() {
            console.log('开始加载分类数据...');
            $.ajax({
                url: '/admin/cms/post/categories',
                type: 'GET',
                success: function(result) {
                    console.log('分类API响应:', result);
                    if (result.success) {
                        console.log('分类数据:', result.data);
                        
                        // 转换数据格式为树形组件需要的格式
                        function convertToTreeData(categories) {
                            return categories.map(function(category) {
                                return {
                                    id: category.id,
                                    title: category.title,
                                    children: category.children && category.children.length > 0 ? convertToTreeData(category.children) : []
                                };
                            });
                        }
                        
                        const treeData = convertToTreeData(result.data);
                        console.log('树形数据:', treeData);
                        
                        // 渲染树形组件
                        tree.render({
                            elem: '#category-tree-content',
                            data: treeData,
                            showLine: true,
                            click: function(obj) {
                                console.log('选择分类:', obj.data);
                                $('#category-display').val(obj.data.title);
                                $('#category-id').val(obj.data.id);
                                $('#category-tree').hide();
                            }
                        });
                        
                        // 绑定点击事件
                        $('#category-display').click(function() {
                            $('#category-tree').toggle();
                            if ($('#category-tree').is(':visible')) {
                                $('#category-search').focus();
                            }
                        });
                        
                        // 点击其他地方隐藏树形组件
                        $(document).click(function(e) {
                            if (!$(e.target).closest('#category-display, #category-tree').length) {
                                $('#category-tree').hide();
                            }
                        });
                        
                        // 搜索功能
                        $('#category-search').on('input', function() {
                            const searchText = $(this).val().toLowerCase().trim();
                            console.log('搜索文本:', searchText);
                            
                            if (!searchText) {
                                // 如果搜索框为空，显示所有分类
                                tree.render({
                                    elem: '#category-tree-content',
                                    data: treeData,
                                    showLine: true,
                                    click: function(obj) {
                                        console.log('选择分类:', obj.data);
                                        $('#category-display').val(obj.data.title);
                                        $('#category-id').val(obj.data.id);
                                        $('#category-tree').hide();
                                    }
                                });
                                return;
                            }
                            
                            // 搜索匹配的分类
                            function searchCategories(categories, searchText) {
                                let results = [];
                                
                                for (let category of categories) {
                                    // 检查当前分类是否匹配
                                    if (category.title.toLowerCase().includes(searchText)) {
                                        results.push({
                                            id: category.id,
                                            title: category.title,
                                            children: []
                                        });
                                    }
                                    
                                    // 递归搜索子分类
                                    if (category.children && category.children.length > 0) {
                                        const childResults = searchCategories(category.children, searchText);
                                        results = results.concat(childResults);
                                    }
                                }
                                
                                return results;
                            }
                            
                            const searchResults = searchCategories(treeData, searchText);
                            console.log('搜索结果:', searchResults);
                            
                            // 渲染搜索结果
                            if (searchResults.length > 0) {
                                tree.render({
                                    elem: '#category-tree-content',
                                    data: searchResults,
                                    showLine: true,
                                    click: function(obj) {
                                        console.log('选择分类:', obj.data);
                                        $('#category-display').val(obj.data.title);
                                        $('#category-id').val(obj.data.id);
                                        $('#category-tree').hide();
                                    }
                                });
                            } else {
                                // 没有搜索结果
                                $('#category-tree-content').html('<div style="padding: 20px; text-align: center; color: #999;">没有找到匹配的分类</div>');
                            }
                        });
                        
                        // 搜索框回车键处理
                        $('#category-search').on('keydown', function(e) {
                            if (e.keyCode === 13) { // Enter键
                                e.preventDefault();
                                const firstResult = $('#category-tree-content .layui-tree-txt').first();
                                if (firstResult.length > 0) {
                                    firstResult.click();
                                }
                            }
                        });
                        
                        console.log('分类数据加载完成');
                    } else {
                        console.error('分类API返回失败:', result.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载分类失败:', xhr, status, error);
                    layer.msg('加载分类失败', {icon: 2});
                }
            });
        }

        // 加载标签数据
        function loadTags() {
            console.log('开始加载标签数据...');
            $.ajax({
                url: '/admin/cms/post/tags',
                type: 'GET',
                success: function(result) {
                    console.log('标签API响应:', result);
                    if (result.success) {
                        allTags = result.data;
                        console.log('标签数据:', allTags);
                        console.log('标签数量:', allTags.length);
                    } else {
                        console.error('标签API返回失败:', result.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载标签失败:', xhr, status, error);
                    layer.msg('加载标签失败', {icon: 2});
                }
            });
        }

        // 显示标签选择弹窗
        function showTagSelector() {
            let tagHtml = '<div style="padding: 20px;">';
            tagHtml += '<div class="layui-form-item">';
            tagHtml += '<label class="layui-form-label">搜索标签</label>';
            tagHtml += '<div class="layui-input-block">';
            tagHtml += '<input type="text" id="tag-search" placeholder="输入标签名称搜索" class="layui-input">';
            tagHtml += '</div>';
            tagHtml += '</div>';
            tagHtml += '<div id="tag-list" style="max-height: 300px; overflow-y: auto;">';
            
            allTags.forEach(function(tag) {
                const isSelected = selectedTags.some(t => t.id === tag.id);
                tagHtml += `<div class="layui-form-item">`;
                tagHtml += `<input type="checkbox" name="tag_${tag.id}" value="${tag.id}" title="${tag.title || tag.name || '未命名标签'}" ${isSelected ? 'checked' : ''}>`;
                tagHtml += `<label style="margin-left: 10px;">${tag.title || tag.name || '未命名标签'}</label>`;
                tagHtml += `</div>`;
            });
            
            tagHtml += '</div></div>';
            
            layer.open({
                type: 1,
                title: '选择标签',
                content: tagHtml,
                area: ['500px', '400px'],
                btn: ['确定', '取消'],
                yes: function(index) {
                    // 获取选中的标签
                    const checkedTags = [];
                    allTags.forEach(function(tag) {
                        if ($(`input[name="tag_${tag.id}"]`).is(':checked')) {
                            checkedTags.push(tag);
                        }
                    });
                    
                    selectedTags = checkedTags;
                    renderSelectedTags();
                    layer.close(index);
                }
            });
            
            // 绑定搜索功能
            $('#tag-search').on('input', function() {
                const searchText = $(this).val().toLowerCase();
                allTags.forEach(function(tag) {
                    const checkbox = $(`input[name="tag_${tag.id}"]`);
                    const item = checkbox.closest('.layui-form-item');
                    if (tag.title.toLowerCase().includes(searchText)) {
                        item.show();
                    } else {
                        item.hide();
                    }
                });
            });
            
            form.render('checkbox');
        }

        // 渲染已选择的标签
        function renderSelectedTags() {
            const container = $('#selected-tags');
            container.empty();
            
            console.log('渲染标签，当前标签数据:', selectedTags);
            console.log('标签数量:', selectedTags ? selectedTags.length : 0);
            
            if (selectedTags && selectedTags.length > 0) {
                selectedTags.forEach(function(tag) {
                    const tagTitle = tag.title || tag.name || '未命名标签';
                    console.log(`渲染标签: ${tagTitle} (ID: ${tag.id})`);
                    container.append(`
                        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" data-tag-id="${tag.id}">
                            ${tagTitle}
                            <i class="layui-icon layui-icon-close" onclick="removeTag(${tag.id})"></i>
                        </button>
                    `);
                });
            }
        }

        // 移除标签
        function removeTag(tagId) {
            selectedTags = selectedTags.filter(tag => tag.id !== tagId);
            renderSelectedTags();
        }

        // 绑定标签按钮事件
        $('#add-tag-btn').click(function() {
            showTagSelector();
        });

        // 特色图像功能
        // 上传图片
        $('#upload-featured-image').click(function() {
            // 创建一个隐藏的文件输入框
            let fileInput = $('<input type="file" accept="image/*" style="display: none;">');
            $('body').append(fileInput);
            
            fileInput.click();
            
            fileInput.on('change', function() {
                let file = this.files[0];
                if (file) {
                    // 创建FormData对象
                    let formData = new FormData();
                    formData.append('image', file);
                    formData.append('type', 'images');
                    
                    // 上传文件
                    $.ajax({
                        url: '/admin/cms/post/upload',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(result) {
                            if (result.errorCode === 0) {
                                let imageUrl = result.data.src;
                                $('#featured-image-url').val(imageUrl);
                                showImagePreview(imageUrl);
                                layer.msg('图片上传成功', {icon: 1});
                            } else {
                                layer.msg(result.msg || '上传失败', {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('上传失败', {icon: 2});
                        }
                    });
                }
                
                // 移除临时文件输入框
                fileInput.remove();
            });
        });
        
        // 粘贴图片地址
        $('#paste-image-url').click(function() {
            layer.prompt({
                title: '请输入图片地址',
                formType: 0,
                value: '',
                area: ['400px', '150px']
            }, function(value, index) {
                if (value && value.trim()) {
                    $('#featured-image-url').val(value.trim());
                    showImagePreview(value.trim());
                    layer.close(index);
                    layer.msg('图片地址已设置', {icon: 1});
                } else {
                    layer.msg('请输入有效的图片地址', {icon: 2});
                }
            });
        });
        
        // 移除特色图像
        $('#remove-featured-image').click(function() {
            $('#featured-image-url').val('');
            $('#featured-image-preview').hide();
            layer.msg('特色图像已移除', {icon: 1});
        });
        
        // 显示图片预览
        function showImagePreview(imageUrl) {
            if (imageUrl && imageUrl.trim()) {
                $('#preview-img').attr('src', imageUrl);
                $('#featured-image-preview').show();
            } else {
                $('#featured-image-preview').hide();
            }
        }
        
        // 监听图片地址输入框变化
        $('#featured-image-url').on('input', function() {
            let imageUrl = $(this).val().trim();
            showImagePreview(imageUrl);
        });
        
        // 初始化特色图像预览（如果有值）
        let initialImageUrl = $('#featured-image-url').val();
        if (initialImageUrl) {
            showImagePreview(initialImageUrl);
        }

        // 草稿按钮事件处理
        form.on('submit(post-save)', function(data) {
            console.log('草稿按钮事件触发', data);
            
            // 获取EasyMDE内容
            let markdownContent = easyMDE.value();
            
            // 构建提交数据
            let submitData = {
                title: data.field.title,
                slug: data.field.slug,
                excerpt: data.field.excerpt,
                featured_image: data.field.featured_image || '',
                content: markdownContent,
                category_id: data.field.category_id ? parseInt(data.field.category_id) : null,
                tag_ids: selectedTags.map(tag => tag.id),
                meta_title: data.field.meta_title || '',
                meta_keywords: data.field.meta_keywords || '',
                meta_description: data.field.meta_description || '',
                type: data.field.type || 'markdown',  // 文章类型
                status: 'draft'  // 保存为草稿
            }
            
            console.log('准备提交的数据:', submitData);
            console.log('提交URL:', '/admin/cms/post/save');
            
            $.ajax({
                url: '/admin/cms/post/save',
                data: JSON.stringify(submitData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function(result) {
                    if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))
                            parent.layui.table.reload('post-table')
                        })
                    } else {
                        layer.msg(result.msg, { icon: 2, time: 1000 })
                    }
                },
                error: function (xhr, status, error) {
                    layer.msg('保存失败: ' + error, { icon: 2, time: 2000 })
                }
            })
            return false
        })
        
        // 发布按钮事件处理
        $('#publish-btn').click(function() {
            console.log('发布按钮事件触发');
            
            // 获取表单数据
            let formData = {};
            $('form.layui-form input, form.layui-form textarea, form.layui-form select').each(function() {
                let name = $(this).attr('name');
                let value = $(this).val();
                if (name) {
                    formData[name] = value;
                }
            });
            
            console.log('获取到的表单数据:', formData);
            
            // 获取EasyMDE内容
            let markdownContent = easyMDE.value();
            
            // 构建提交数据
            let submitData = {
                title: formData.title,
                slug: formData.slug,
                excerpt: formData.excerpt,
                featured_image: formData.featured_image || '',
                content: markdownContent,
                category_id: formData.category_id ? parseInt(formData.category_id) : null,
                tag_ids: selectedTags.map(tag => tag.id),
                meta_title: formData.meta_title || '',
                meta_keywords: formData.meta_keywords || '',
                meta_description: formData.meta_description || '',
                type: formData.type || 'markdown',  // 文章类型
                status: 'published'  // 发布状态
            }
            
            console.log('准备发布的数据:', submitData);
            console.log('发布URL:', '/admin/cms/post/save');
            
            $.ajax({
                url: '/admin/cms/post/save',
                data: JSON.stringify(submitData),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function(result) {
                    if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))
                            parent.layui.table.reload('post-table')
                        })
                    } else {
                        layer.msg(result.msg, { icon: 2, time: 1000 })
                    }
                },
                error: function (xhr, status, error) {
                    layer.msg('发布失败: ' + error, { icon: 2, time: 2000 })
                }
            })
        })

        // 初始化
        loadCategories();
        loadTags();
        renderSelectedTags();
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});
</script>
</body>
</html>